<?php

namespace app\agent\model;

use think\facade\Db;

class BalanceChangeApply
{
    private $table = 'agent_balance_change_apply';
    /**
     * 列表.
     */
    public function getList($params)
    {
        $where = [];
        $where[] = ['agent_id', '=', $params['agent']['id']];
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $createdDate = $params['created_at'] ?? [];
        if (is_array($createdDate) && !empty($createdDate[0]) && $createdDate[1]) {
            $where[] = ['created_at', 'between time', [$createdDate[0], $createdDate[1] . ' 23:59:59']];
        }
        $list = Db::name($this->table)
            ->where($where)
            ->order('id desc')
            ->paginate($paginate)
            ->toArray();

        return success('操作成功', $list);
    }

    /**
     * 添加.
     */
    public function create($params)
    {
        $amount = trim($params['amount']);
        $amount = floatval($amount);
        if ($amount == 0) {
            return fail('申请金额不能为 0');
        }
        $amount = yuan2fen($params['amount']);
        $absAmount = abs($amount);
        if ($absAmount > 100000000) {
            return fail('申请金额范围 -100万 ～ 100万');
        }

        Db::startTrans();
        try {
            $id = Db::name($this->table)
                ->insertGetId([
                    'agent_id' => $params['agent']['id'],
                    'amount' => $amount,
                    'username' => $params['username'],
                    'bank_name' => $params['bank_name'],
                    'image' => $params['image'] ?? '',
                    'remark' => $params['remark'] ?? '',
                ]);

            if ($amount < 0) {
                $balance = Db::name('agent')
                    ->where('id', $params['agent']['id'])
                    ->value('balance');
                if ($balance < $absAmount) {
                    return fail('账户余额不足');
                }
                $res = Db::name('agent')
                    ->where('id', $params['agent']['id'])
                    ->where('balance', '>=', $absAmount)
                    ->dec('balance', $absAmount)
                    ->inc('freeze_amount', $absAmount)
                    ->update([
                        'balance_last_updated_at' => date('Y-m-d H:i:s'),
                    ]);
                if (!$res) {
                    Db::rollback();
                    return fail('账户余额不足。');
                }
                Db::name('agent_balance_log')
                    ->insert([
                        'agent_id' => $params['agent']['id'],
                        'type' => BALANCE_CHANGE_APPLY,
                        'amount' => $amount,
                        'old_balance' => $balance,
                        'new_balance' => $balance + $amount,
                        'remark' => '加款申请：' . fen2yuan($amount),
                        'quote_id' => $id,
                    ]);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('申请失败，请重试：' . $e->getMessage());
        }

        return success('申请成功');
    }

    /**
     * 撤销加款申请
     */
    public function cancel($params)
    {
        $info = Db::name($this->table)
            ->where('id', $params['id'])
            ->where('agent_id', $params['agent']['id'])
            ->find();
        if (empty($info)) {
            return fail('加款申请记录不存在');
        }

        if ($info['status'] != 1) {
            return fail('当前记录无法撤销[' . $info['status'] . ']');
        }

        // 防止重复撤销
        $tempStatus = 21;
        $res = Db::name($this->table)
            ->where('id', $params['id'])
            ->where('status', 1)
            ->update([
                'status' => $tempStatus,
            ]);
        if (!$res) {
            return fail('撤销失败。' . __LINE__);
        }
        Db::startTrans();
        try {
            $res = Db::name($this->table)
                ->where('id', $params['id'])
                ->where('status', $tempStatus)
                ->update([
                    'status' => 4,
                ]);
            if (!$res) {
                Db::rollback();
                return fail('撤销失败。' . __LINE__);
            }

            // 如果申请金额小于 0，需要补回去
            if ($info['amount'] < 0) {
                $absAmount = abs($info['amount']);
                $balance = Db::name('agent')
                    ->where('id', $params['agent']['id'])
                    ->value('balance');
                $res = Db::name('agent')
                    ->where('id', $params['agent']['id'])
                    ->where('freeze_amount', '>=', $absAmount)
                    ->inc('balance', $absAmount)
                    ->dec('freeze_amount', $absAmount)
                    ->update([
                        'balance_last_updated_at' => date('Y-m-d H:i:s'),
                    ]);
                if (!$res) {
                    Db::rollback();
                    return fail('冻结金额不足，撤销失败。' . $absAmount);
                }
                Db::name('agent_balance_log')
                    ->insert([
                        'agent_id' => $params['agent']['id'],
                        'type' => BALANCE_CHANGE_APPLY,
                        'amount' => $absAmount,
                        'old_balance' => $balance,
                        'new_balance' => $balance + $absAmount,
                        'remark' => '撤销加款申请：' . fen2yuan($absAmount),
                        'quote_id' => $info['id'],
                    ]);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('撤销失败。' . $e->getMessage());
        }

        return success('撤销成功');
    }
}
